<template>
  <div class="main">
    <div class="scan" @click="scanHandle" v-if="assetsFlag"/>
    <basic-layout title="开始报修" :showAddBtn="false" class="wrapBox">
      <van-form ref="form" class="vanForm">
        <div v-if="isScan && assetsFlag">
          <div v-if="formData.type == '03'">
            <!--楼宇设备-->
            <van-field readonly
                       label="设备名称"
                       name="设备名称">
              <template #input>
                <div>
                  <span>{{ formData.swLysbLouysbxxName }}</span>
                </div>
              </template>
            </van-field>
          </div>
          <div v-if="formData.type == '05'">
            <!--服务设备-->
            <van-field readonly
                       label="设备品名"
                       name="设备品名">
              <template #input>
                <div>
                  <span>{{ formData.swFuwsbPinm }}</span>
                </div>
              </template>
            </van-field>
          </div>
        </div>
        <van-field v-model="formData.appName"
                   required
                   label="姓名"
                   name="姓名"
                   placeholder="请输入报修人姓名"
                   :rules="ruleForm.appName"/>

        <van-field v-model="formData.appPhone"
                   required
                   label="手机号码"
                   name="电话"
                   placeholder="请输入报修人手机号码"
                   :rules="ruleForm.appPhone"/>

        <van-field readonly
                   clickable
                   name="picker"
                   :value="formData.fdzyXxjjfcxxName"
                   label="报修区域"
                   placeholder="点击选择报修区域"
                   @click="showPicker = true"
                   v-if="assetsFlag"/>

        <van-field v-model="formData.repairAddr"
                   required
                   label="详细地址"
                   rows="2"
                   autosize
                   type="textarea"
                   maxlength="30"
                   placeholder="请输入详细地址"
                   show-word-limit
                   :rules="ruleForm.repairAddr"/>

        <van-field v-model="formData.repairDesc"
                   required
                   label="故障描述"
                   rows="3"
                   autosize
                   type="textarea"
                   maxlength="40"
                   placeholder="请输入故障描述"
                   show-word-limit
                   :rules="ruleForm.repairDesc"/>

        <div class="imgBox">
          <div>请上传故障图片</div>
          <van-field name="uploader" class="picStyle">
            <template #input>
<!--              <van-uploader :accept="accept"-->
<!--                            :before-read="uploadBefore"-->
<!--                            :before-delete="onDel"-->
<!--                            v-model="fileList"-->
<!--                            :max-count="6"/>-->
              <uploadCom ref="uploadRef"
                         :maxNumber="6"
                         @uploadFileIds="uploadFileIds"
                         accept=".png,.jpg,.jpeg"
                         :defaultFiles="defaultFiles" />
            </template>
          </van-field>
        </div>

        <van-field name="radio"
                   label="报修类型"
                   required
                   :rules="ruleForm.repairType">
          <template #input>
            <van-radio-group v-model="formData.repairType"
                             @change="changeRepairType"
                             v-for="item in employRepairTypeList"
                             direction="horizontal">
              <van-radio :name="item.value">{{ item.valueAlias }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </van-form>

      <van-button class="defaultBtn" size="large" color="#4eb3e9" @click="onSubmit">提交</van-button>
<!--      <div class="foot">-->
<!--        <van-button class="button"-->
<!--                    round-->
<!--                    type="primary"-->
<!--                    block-->
<!--                    @click="onSubmit">-->
<!--          提交-->
<!--        </van-button>-->
<!--      </div>-->
    </basic-layout>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker title="请选择报修区域"
                  show-toolbar
                  :columns="columns"
                  @confirm="onConfirm"
                  @cancel="showPicker = false">
        <template #option="option">
          <div style="display: flex; flex-direction: column; align-items: center;">
            <div>{{ option.fangcname }}</div>
          </div>
        </template>
      </van-picker>

    </van-popup>

  </div>
</template>
<script>
import {uploadAttach} from "@api/common";
import {
  getUserInfo,
  apply,
  checkAssetsFlag,
  getPreRepairInfo,
  getFdzyXxjjfcxxs,
} from "@api/srvAssurance/convApp";
import {getDetailBySwid, queryShebListByParams, queryFwsb, guzbxsbfindAll} from "@api/srvAssurance/assetLabel/assetLabel";
import {queryDic} from "@api/common";


export default {
  name: 'applyRepair',
  props: {},
  components: {},
  data() {
    return {
      defaultFiles: [],
      assetsFlag: false,
      columns: [],
      isScan: false,
      showPicker: false,
      employRepairTypeList: [],

      accept: ".png,.jpg,.jpeg",
      maxSize: 51200, // 文件最大：50M
      fileList: [],
      formData: {
        swid: '',
        swLysbLouysbxxId: '',
        swLysbLouysbxxName: '',
        appName: '',
        appPhone: '',
        fdzyXxjjfcxxId: '',   // 楼宇标识
        fdzyXxjjfcxxName: '', //  楼宇名称
        repairAddr: '',
        swFuwsbId: '',
        swFuwsbPinm: '',
        type: '',
        repairDesc: '',
        repairType: '1',
        fileCode: [],// 文件
      },
      formDataBack: {
        appName: '',
        appPhone: '',
      },
      // 必填项校验
      ruleForm: {
        appName: [
          {required: true, message: "请输入报修人姓名", trigger: "onBlur"},
        ],
        appPhone: [
          {required: true, message: "请输入报修人手机号码", trigger: "onBlur"},
          {
            pattern: this.$commonReg.phoneReg,
            message: this.$commonReg.phoneMsg,
            trigger: "onBlur",
          },
        ],
        repairArea: [
          {required: false, message: "请选择报修区域", trigger: "onChange"},
        ],
        repairAddr: [
          {required: true, message: "请输入详细地址", trigger: "onBlur"},
        ],
        repairDesc: [
          {required: true, message: "请输入故障描述", trigger: "onBlur"},
        ],
        repairType: [
          {required: true, message: "请选择报修类型", trigger: "onChange"},
        ],
      },
    }
  },
  created() {
    this.reset();
    this.initData();
  },
  computed: {},
  mounted() {
  },
  methods: {

    // 附件上传
    uploadFileIds (arr) {
      this.formData.fileCode = arr;
    },

    // // 附件上传之前（进行附件大小、类型验证）
    // uploadBefore(file) {
    //   let format = this.accept.replace(/\./g, '').split(",");
    //   if ((file.size / 1000) > this.maxSize) {
    //     this.$Notify({type: "warning", message: `文件大小不能超过${(this.maxSize / 1024)}M!`});
    //     return false;
    //   } else if (!format.includes((file.name.split('.')[file.name.split('.').length - 1]).toLowerCase())) {
    //     this.$Notify({type: "warning", message: '文件格式有误,请上传' + format.join('、') + '格式文件！'});
    //     return false;
    //   }
    //   uploadAttach(file).then(res => {
    //     if (res.code === 1000 && res.data) {
    //       this.fileList.push({url: res.data.url});
    //       this.formData.fileCode.push(res.data.fileCode);
    //     }
    //   })
    // },
    // // 文件删除前的
    // onDel(file, obj) {
    //   this.fileList.splice(obj.index, 1);
    //   this.formData.fileCode.splice(obj.index, 1);
    // },

    scanHandle() {
      let _this = this;
      wx.scanQRCode({
        desc: "scanQRCode desc",
        needResult: 1, // 默认为0，扫描结果由i国网处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: async function (res) {
          if (res.resultStr) {
            let  queryParam = {};
            queryParam.swid = res.resultStr;
            let resData = await getDetailBySwid(queryParam);
            if (resData.status == 0) {
              let item = resData.data[0];
              if (item.shebType == "03") {
                // console.log("楼宇设备");
                _this.queryLouyEquipment(res.resultStr);
              } else if (item.shebType == "05") {
                // console.log("服务设备");
                _this.queryFuwEquipment(res.resultStr);
              } else {
                this.$Notify({type: "warning", message: '请选择楼宇设备或者服务设备的二维码！'});
              }
            }
          }
        },
        error: function (res) {
          if (res.errMsg.indexOf("function_not_exist") > 0) {
            alert("版本过低请升级");
          }
        },
      });
    },

    async queryLouyEquipment(swid) {
      let queryParam = {};
      queryParam.pageIndex = 1;
      queryParam.pageSize = 10;
      queryParam.searchSwid = swid;
      await guzbxsbfindAll(queryParam).then(res => {
        if (res.data.length > 0) {
          let item = res.data[0];
          this.formData.swLysbLouysbxxId = item.ID;
          this.formData.swLysbLouysbxxName = item.SBMC;

          this.isScan = true;
          this.formData.type = '03';
          this.formData.swid = swid;
        } else {
          this.$Notify({type: "warning", message: '未查询到设备信息！'});
        }
      })
    },

    async queryFuwEquipment(swid) {
      let queryParam = {};
      queryParam.sbdl = '';
      queryParam.sbxl = '';
      queryParam.searchPinm = '';
      queryParam.searchSwid = '';
      queryParam.page = 1;
      queryParam.rows = 10;
      queryParam.swid = swid;
      await queryFwsb(queryParam).then(res => {
        if (res.data.length > 0) {
          let item = res.data[0];
          this.formData.swFuwsbId = item.ID;
          this.formData.swFuwsbPinm = item.PINM;

          this.isScan = true;
          this.formData.type = '05';
          this.formData.swid = swid;
        } else {
          this.$Notify({type: "warning", message: '未查询到设备信息！'});
        }
      })
    },

    // 提交
    onSubmit() {
      // 全局表单验证
      this.$refs.form.validate().then(async () => {
        let obj = {...this.formData}
        apply(obj).then(res => {
          this.$Notify({type: 'success', message: '保存成功！'});
          this.$router.go(-1);
        })
      }).catch(() => {
        // this.$toast.fail('请完成必填项！')
      })
    },

    onConfirm(value) {
      this.formData.fdzyXxjjfcxxId = value.id;
      this.formData.fdzyXxjjfcxxName = value.fangcname;
      this.showPicker = false;
    },

    changeRepairType(val) {
      if (val == '1') {
        this.formData.appPhone = this.formDataBack.appPhone;
        this.formData.appName = this.formDataBack.appName;
      } else {
        this.formData.appPhone = '';
        this.formData.appName = '';
      }
    },

    reset() {
      this.formData = {
        swid: '',
        swLysbLouysbxxId: '',
        swLysbLouysbxxName: '',
        appName: '',
        appPhone: '',
        fdzyXxjjfcxxId: '',   // 楼宇标识
        fdzyXxjjfcxxName: '', //  楼宇名称
        repairAddr: '',
        swFuwsbId: '',
        swFuwsbPinm: '',
        type: '',
        repairDesc: '',
        repairType: '1',
        fileCode: [],// 文件
      }

      this.assetsFlag = false;
      this.columns = [];
      this.isScan = false;
      this.showPicker = false;
      this.employRepairTypeList = [];
      setTimeout(() => {
        this.$refs.form.resetValidation();
      });
    },

    // 下拉框数据
    initData() {
      getUserInfo().then(res => {
        if (res.code === 1000 && res.data) {
          this.formDataBack.appName = res.data.appName;
          this.formDataBack.appPhone = res.data.appPhone;
          this.formData.appName = res.data.appName;
          this.formData.appPhone = res.data.appPhone;
        }
      });
      checkAssetsFlag().then(res => {
        if (res.code === 1000 && res.data) {
          this.assetsFlag = res.data;
        }
      });
      getFdzyXxjjfcxxs().then(res => {
        if (res.code === 1000 && res.data) {
          this.columns = res.data;
        }
      });
      getPreRepairInfo().then(res => {
        if (res.code === 1000 && res.data) {
          this.formData.fdzyXxjjfcxxId = res.data.fdzyXxjjfcxxId || '';
          this.formData.fdzyXxjjfcxxName = res.data.fdzyXxjjfcxxName || '';
        }
      });
      queryDic('SA_EMPLOY_REPAIR_TYPE_CODE').then(res => {
        if (res.code === 1000 && res.data) {
          this.employRepairTypeList = res.data;
        }
      });
    },

  },
}
</script>
<style lang="less" scoped>
.vanForm {
  overflow-y: auto;
  margin-bottom: 15px;

  .imgBox {
    padding: 16px;
    position: relative;

    &:before {
      position: absolute;
      left: 0.21333rem;
      color: #ee0a24;
      font-size: 0.37333rem;
      content: '*';
    }

    &:after {
      position: absolute;
      box-sizing: border-box;
      content: ' ';
      pointer-events: none;
      right: 0.42667rem;
      bottom: 0;
      left: 0.42667rem;
      border-bottom: 0.02667rem solid #ebedf0;
      -webkit-transform: scaleY(.5);
      transform: scaleY(.5);
    }

    .picStyle {
      padding: 16px 0px 16px 0px !important;
    }

  }
}

.foot {
  position: absolute;
  width: 100%;
  background: #ffffff;
  padding: 10px 0;
  right: 0px;
  bottom: 0px;
  height: 45px;
  z-index: 1;

  .button {
    color: #ffffff;
    border-radius: 20px;
    height: 45px;
    line-height: 45px;
    width: 120px;
    font-size: 17px;
    width: 80%;
    margin-left: 10%;
  }
}

.scan {
  background-image: url('../../../../assets/images/nx/saoyisao.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 26px;
  height: 26px;
  margin-top: 10px;
  margin-left: 88%;
  position: absolute;
  z-index: 9999;
  color: rgb(51, 51, 51);
}
</style>
